package thesis.prototype;

import java.util.List;
import java.util.ArrayList;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;

import thesis.prototype.objects.ConnectPHP;
import thesis.prototype.objects.Contact;

public class ShowMapActivity extends MapActivity implements OnClickListener {
    /** Called when the activity is first created. */
	
	//Buttons
	private Button b_dest_prev; //DEST --> ORG
	private Button b_dest_next; //DEST --> Send Message
	private Button b_dest_cancel; //DEST --> START
	
	//MapView
	private MapView mapView;
	private MapController mvController;
	private GeoPoint startPoint;
	private POIOverlay pointsOfInterest;
	private POIOverlay inviteePoints;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dest);

        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        
        mvController = mapView.getController();  
        startPoint = getPoint(14.638317,121.0772);
        mvController.setCenter(startPoint);

        ConnectPHP con = ConnectPHP.getInstance();
        ArrayList<thesis.prototype.objects.Location> locs = con.getLocations();
        pointsOfInterest = new POIOverlay( locs, R.drawable.blue_full_marker );
        mapView.getOverlays().add(pointsOfInterest);
		
        locs = con.getInviteeMapLocations();
        inviteePoints = new POIOverlay( locs, R.drawable.man );
        inviteePoints.displayUserLoc();
		mapView.getOverlays().add(inviteePoints);
		
        mvController.setZoom(18); // optional?
        mapView.invalidate();
       
        b_dest_prev = (Button) findViewById(R.id.dest_prev);
		b_dest_next = (Button) findViewById(R.id.dest_next);
		b_dest_cancel = (Button) findViewById(R.id.dest_cancel);
		addButtonListeners();
    }
    
    @Override 
    protected boolean isRouteDisplayed() {
        return false;
    }
    
    private void addButtonListeners()
	{
    	if (b_dest_prev != null) b_dest_prev.setOnClickListener(this);
		if (b_dest_next != null) b_dest_next.setOnClickListener(this);
		if (b_dest_cancel != null) b_dest_cancel.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		if(view==b_dest_cancel)
		{
			setResult(RESULT_CANCELED);
			finish();
		}
		else if(view==b_dest_prev)
		{
			setResult(RESULT_FIRST_USER);
			finish();
		}
		else if(view==b_dest_next)
		{
			if( pointsOfInterest.getSelectedLocID().equals("") ) {
				Toast t = Toast.makeText(this, "Select one meeting location", Toast.LENGTH_LONG);
				t.show();
			}
			else {
				Dialog sendAlertDialog = this.sendAlert();
				sendAlertDialog.show();
			}
		}
	}
	
	private void setMeeting()
	{
		ConnectPHP con = ConnectPHP.getInstance();
		
		String title = HelloActivity.meet_title;
		String datetime = HelloActivity.meet_date + " " + HelloActivity.meet_time;
		String loc_id = pointsOfInterest.getSelectedLocID();
		
		TelephonyManager teleManager =(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		String number = teleManager.getLine1Number();
		
		con.setMeeting(number, title, datetime, loc_id);
	}
    
	private void sendInvites()
	{	
		// SMS sending
		for( Contact c: HelloActivity.arr_invited)
		{
			sendSms(c.getNumber(), SMSReceiver.MEET_ME_MSG);
		}
	}
	
	private void sendSms(String number, String message)
	{
		/*PendingIntent pi = PendingIntent.getActivity(this, 0,
	            new Intent(this, ShowMapActivity.class), 0);                
	    SmsManager sms = SmsManager.getDefault();
	    sms.sendTextMessage(number, null, message, pi, null); */
		
		String SENT = "SMS_SENT";
		
		PendingIntent sentPI = PendingIntent.getBroadcast(this,
				0, new Intent(SENT), 0);
		
		/*registerReceiver(new BroadcastReceiver()
		{
			@Override
			public void onReceive(Context con, Intent intent)
			{
				switch(getResultCode())
				{
				case Activity.RESULT_OK:
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
				case SmsManager.RESULT_ERROR_NO_SERVICE:
				case SmsManager.RESULT_ERROR_NULL_PDU:
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					unsent.add(intent.getStringExtra("address"));
					break;
				}
				
			}
		}
		
		, new IntentFilter(SENT)); */
		
		SmsManager sms = SmsManager.getDefault();
	    sms.sendTextMessage(number, null, message, sentPI, null);
	}
	
	private Dialog sendAlert(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Send meeting request to attendees? This will incur SMS costs.")
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                // setContentView(R.layout.start);
		        	   setMeeting();
		        	   sendInvites();
		        	   setResult(RESULT_OK);
		        	   finish();
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		
		return alert;
	}
	
	private GeoPoint getPoint(double lat, double lon) {
		return(new GeoPoint((int)(lat*1000000.0), (int)(lon*1000000.0)));
	}
	
	private class POIOverlay extends ItemizedOverlay<MapItem> {

		private List<MapItem> items = new ArrayList<MapItem>();
		
		public POIOverlay( ArrayList<thesis.prototype.objects.Location> locs, int resource ) 
		{
			super(null);
			
	        try {
	        	MapItem poi;
				for( int i = 0; i < locs.size(); i++ ) {
					thesis.prototype.objects.Location loc = locs.get(i);
					poi = new MapItem( getPoint(loc.getLatitude(), loc.getLongitude()),
							loc.getName(), "", getMarker(resource), 
							loc.getLoc_id() );
					items.add(poi);
				}
			
	        } catch ( Exception e ) { }
	        
			populate();
		}
		
		public String getSelectedLocID()
		{
			MapItem item = (MapItem) getFocus();
			if( item != null )
				return item.getLocID();
			else
				return "";
		}	
		
		public void displayUserLoc()
		{
			// get current location
			Location loc = LocationUpdaterService.getCurrentLocation();
			if( loc != null ) {
				MapItem userPoint = new MapItem( getPoint(loc.getLatitude(), loc.getLongitude()),
						"Me", "", getMarker(R.drawable.man), "" );
				items.add(userPoint);
				populate();
			}
		}
		
		@Override
		protected MapItem createItem(int i) {
			return items.get(i);
		}
		
		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			super.draw(canvas, mapView, shadow);
		}
		
		@Override
		public int size() {
			return items.size();
		}
		
		private Drawable getMarker(int resource) {
			Drawable marker=getResources().getDrawable(resource);
			marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
			boundCenter(marker);
			return marker;
		}
	}
	
	class MapItem extends OverlayItem {
		Drawable marker;
		String loc_id;
		
		public MapItem(GeoPoint point, String name, String snippet,
							 Drawable marker, String loc_id) {
			super(point, name, snippet);
			
			setMarker(marker);
			this.loc_id = loc_id;
		}
		
		public String getLocID() {
			return loc_id;
		}
	}
}